package com.tzkyzj.tiremanager.interceptor;

import com.tzkyzj.tiremanager.entity.User;
import com.tzkyzj.tiremanager.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private AuthService authService;

    // 不需要登录的接口和页面
    private static final List<String> EXCLUDE_PATHS = Arrays.asList(
            "/api/auth/login",
            "/api/auth/logout",
            "/login",
            "/css/",
            "/js/",
            "/images/",
            "/webjars/",
            "/error"
    );

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getRequestURI();
        String contextPath = request.getContextPath();

        // 移除上下文路径
        if (contextPath != null && path.startsWith(contextPath)) {
            path = path.substring(contextPath.length());
        }

        // 检查是否在排除列表中
        if (EXCLUDE_PATHS.stream().anyMatch(path::startsWith)) {
            return true;
        }

        User user = null;

        // 首先从Session中获取用户信息
        HttpSession session = request.getSession(false);
        if (session != null) {
            user = (User) session.getAttribute("currentUser");
            System.out.println("从Session获取用户: " + (user != null ? user.getUsername() : "null"));
        }

        // 如果Session中没有，尝试从Token获取
        if (user == null) {
            String token = request.getHeader("Authorization");
            if (token != null && !token.isEmpty()) {
                System.out.println("尝试使用Token验证: " + token);
                user = authService.validateToken(token);
                // 如果通过Token验证成功，将用户信息存入Session
                if (user != null && session != null) {
                    session.setAttribute("currentUser", user);
                    System.out.println("Token验证成功，用户: " + user.getUsername());
                }
            }
        }

        // 用户未认证
        if (user == null) {
            System.out.println("用户未认证，路径: " + path);
            // 如果是API请求，返回JSON错误
            if (path.startsWith("/api/")) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"success\":false,\"message\":\"未授权访问，请先登录\"}");
                return false;
            } else {
                // 如果是页面请求，重定向到登录页
                response.sendRedirect(contextPath + "/login");
                return false;
            }
        }

        // 将用户信息存入request，供后续使用
        request.setAttribute("currentUser", user);
        return true;
    }
}